package com.weyoung.app.event;


import jakarta.servlet.http.HttpServletRequest;
import lombok.Data;

/**
 * 访问事件类
 * 用于封装每次访问的相关信息
 */
@Data
public class AccessEvent {
    /**
     * 用户ID
     */
    private Integer userId;

    /**
     * 访问的URL
     */
    private String url;

    /**
     * 网络类型
     */
    private String network;

    /**
     * 设备类型
     */
    private String device;

    /**
     * 访问者IP
     */
    private String ip;
    
    /**
     * 从HttpServletRequest创建AccessEvent实例
     *
     * @param request HTTP请求对象
     * @param userId 用户ID
     * @return AccessEvent实例
     */
    public static AccessEvent from(HttpServletRequest request, Integer userId) {
        AccessEvent event = new AccessEvent();
        event.setUserId(userId);
        event.setUrl(request.getRequestURI());
        event.setNetwork(getNetwork(request));
        event.setDevice(getDevice(request));
        event.setIp(getIpAddress(request));
        return event;
    }
    
    /**
     * 获取网络类型
     * 从请求头中获取网络类型信息
     */
    private static String getNetwork(HttpServletRequest request) {
        // 从请求头中获取网络类型，实际项目中需要根据具体的请求头来获取
        String network = request.getHeader("X-Network-Type");
        return network != null ? network : "UNKNOWN";
    }
    
    /**
     * 获取设备类型
     * 根据User-Agent判断设备类型
     */
    private static String getDevice(HttpServletRequest request) {
        String userAgent = request.getHeader("User-Agent");
        if (userAgent == null) return "UNKNOWN";
        
        if (userAgent.contains("iPhone")) {
            return "iPhone";
        } else if (userAgent.contains("Android")) {
            return "Android";
        } else if (userAgent.contains("iPad")) {
            return "iPad";
        }
        return "OTHER";
    }
    
    /**
     * 获取访问者IP地址
     * 依次从多个请求头中获取IP地址
     */
    private static String getIpAddress(HttpServletRequest request) {
        String ip = request.getHeader("X-Forwarded-For");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_CLIENT_IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }
} 